package org.goldfish.distributed_framework.config;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.Properties;

public class ConfigLoader {

    public enum Mode {
        REGISTRY, SERVER, CLIENT
    }

    public static Object loadConfig() {
        int count = 0;
        Object config = null;

        try {
            if (exists("registry.properties")) {
                Properties p = load("registry.properties");
                config = new RegistryConfig(
                        Objects.requireNonNull(
                                p.getProperty("registry.port"),
                                "registry.port 未配置"
                        )
                );
                count++;
            }

            if (exists("server.properties")) {
                Properties p = load("server.properties");
                config = new ServerConfig.Builder()
                        .port(Integer.parseInt(Objects.requireNonNull(p.getProperty("server.port"), "server.port 未配置")))
                        .registryAddress(Objects.requireNonNull(p.getProperty("server.registry"), "server.registry 未配置"))
                        .serviceName(Objects.requireNonNull(p.getProperty("server.service"), "server.service 未配置"))
                        .serviceImpl(Objects.requireNonNull(p.getProperty("server.impl"), "server.impl 未配置"))
                        .build();
                count++;
            }

            if (exists("client.properties")) {
                Properties p = load("client.properties");
                config = new ClientConfig(
                        Objects.requireNonNull(
                                p.getProperty("client.registry"),
                                "client.registry 未配置"
                                ),
                        Objects.requireNonNull(
                                p.getProperty("client.useRemote"),
                                "client.useRemote 未配置"
                        )
                );
                count++;
            }

        } catch (IOException e) {
            throw new RuntimeException("配置加载失败", e);
        }

        if (count != 1) {
            throw new IllegalStateException("配置文件错误：只能存在一个 *.properties 文件，现在有"+count+"个");
        }

        return config;
    }

    private static Properties load(String file) throws IOException {
        Properties p = new Properties();
        try (var input = ConfigLoader.class.getClassLoader().getResourceAsStream(file)) {
            if (input == null) {
                throw new IOException("配置文件未找到: " + file);
            }
            p.load(input);
        }
        return p;
    }

    private static boolean exists(String file) {
        return ConfigLoader.class.getClassLoader().getResource(file) != null;
    }

}
